﻿using System;

namespace XamlingCore.AzureHelper
{
    public class AzureQueueMutex : AzureQueueHelper
    {
        public AzureQueueMutex(string queueAddress)
            :base(queueAddress)
        {
            ClearAll();
        }

        public bool CheckMutex()
        {
            if (GetMessage(false, TimeSpan.Zero) == null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool ReserveMutex()
        {
            AddMessage("mutex");
            return true;
        }

        public bool ReleaseMutex()
        {
            var message = GetMessage(false, TimeSpan.FromSeconds(20));
            if (message != null)
            {
                DeleteQueueMessage(message);
                return true;
            }
            else
            {
                return false;
            }
        }

        public void ClearAll()
        {
            while (GetMessage(true) != null) ;
        }

    }
}
